package com.example.simpletodolist;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class ToDoItemEdit extends FragmentActivity {

	private EditText mTitleText;
	private EditText mBodyText; 
	private Button mDateButton, mTimeButton, addButton, editButton;
	DialogFragment dateFragment = new DatePickerFragments();
	DialogFragment timeFragment = new TimePickerFragments();
	// GregorianCalendar calendar = new GregorianCalendar();
	private long mRowId;
	private boolean isAdd=false;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		isAdd=this.setIsAdd();
        setContentView(R.layout.activity_to_do_item_edit);

		addButton = (Button)findViewById(R.id.addButton);
		editButton = (Button)findViewById(R.id.editButton);
		mTitleText = (EditText)findViewById(R.id.titleValue);
		mBodyText = (EditText)findViewById(R.id.bodyValue);
		mDateButton = (Button)findViewById(R.id.dateButton);
		mTimeButton = (Button)findViewById(R.id.timeButton);
		
		Bundle bundle = getIntent().getExtras();
		if (!isAdd) {
			mTitleText.setText(bundle.getString(ToDoListDatabase.COL_TITLE));
			mBodyText.setText(bundle.getString(ToDoListDatabase.COL_BODY));
			mDateButton.setText(bundle.getString(ToDoListDatabase.COL_DATE));
			mTimeButton.setText(bundle.getString(ToDoListDatabase.COL_TIME));
			mRowId = bundle.getLong(ToDoListDatabase.KEY_ROWID);

			addButton.setVisibility(Button.INVISIBLE);
			editButton.setVisibility(Button.VISIBLE);
		}

		setupButtonListeners();
    }

	private boolean setIsAdd() {
		return getIntent().getExtras()==null;
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

	
	private void updateDatabase() {
		
		ContentValues values = new ContentValues();
		values.put(ToDoListDatabase.COL_TITLE, mTitleText.getText().toString());
		values.put(ToDoListDatabase.COL_BODY, mBodyText.getText().toString());
		values.put(ToDoListDatabase.COL_DATE, mDateButton.getText().toString());
		values.put(ToDoListDatabase.COL_TIME, mTimeButton.getText().toString());
		
		if (mRowId == 0) {
						Uri newUri = getContentResolver().insert(ToDoListProvider.CONTENT_URI, values);
			String newID = newUri.getLastPathSegment();
			this.mRowId=Integer.parseInt(newID);
		} 
		else {
			Uri uri = Uri.withAppendedPath(
					ToDoListProvider.CONTENT_URI, String.valueOf(mRowId));
			getContentResolver().update(uri, values, null, null);
		}

	}

	
	private Intent prepareReturnIntent() {
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		

		bundle.putString(ToDoListDatabase.COL_TITLE, mTitleText.getText().toString());
		bundle.putString(ToDoListDatabase.COL_BODY, mBodyText.getText().toString());
		bundle.putString(ToDoListDatabase.COL_DATE, mDateButton.getText().toString());
		bundle.putString(ToDoListDatabase.COL_TIME, mTimeButton.getText().toString());

		if (mRowId != 0) {
			bundle.putLong(ToDoListDatabase.KEY_ROWID, mRowId);
		}
		
		intent.putExtras(bundle);
		return intent;
	}


	private void setupButtonListeners() {
		this.mDateButton.setOnClickListener(
				new OnClickListener()
				{
					public void onClick(View v){
					    dateFragment.show(getSupportFragmentManager(), "datePicker");
					}
				}
				);
		this.mTimeButton.setOnClickListener(
				new OnClickListener()
				{
					public void onClick(View v){
					    timeFragment.show(getSupportFragmentManager(), "timePicker");
					}
				}
				);
		
		OnClickListener clickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateDatabase();
				Intent i = prepareReturnIntent();
				setResult(RESULT_OK, i);
				doStartAlarmActivityService(i);
				
				finish();
			}
		};
		
		addButton.setOnClickListener(clickListener);
		editButton.setOnClickListener(clickListener);
	}
	
	/*
	 * logcat kept stating a message that 'certain frames were being skipped'
	 * because of too much load on the main thread.
	 * Due to that, figured this was a good place to call the service
	 */
	private void doStartAlarmActivityService(Intent pendingIntent) {
		Intent serviceIntent = new Intent(this, AlarmService.class);
		Bundle bundle = new Bundle();
		bundle.putAll(pendingIntent.getExtras());
		serviceIntent.putExtras(bundle);
		startService(serviceIntent);
	}
	
/*****************************
	 * member class below is used to allow displaying of DatePicker Dialog window
	 * @author Tony
	 *
	 */
	class DatePickerFragments extends DialogFragment
	implements	DatePickerDialog.OnDateSetListener {
		public static final String DATE_FORMAT = "MM/dd/yyyy";

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			Calendar calendar = new GregorianCalendar();
			if(!isAdd)
			{//if We're editing, parse the date and set the calendar according to that
				String date = getIntent().getExtras().getString(ToDoListDatabase.COL_DATE);
				try {
					calendar = DateTimeParser.parse(DATE_FORMAT, date);
				} catch (ParseException e) {
					Log.d("parse error", "error parsing bundle's date string.  Continuing with 'current' calendar.");
					e.printStackTrace();
				}
				catch (Exception ex) {
					Log.d("error in ToDoItemEdit.onCreateDialog()", ex.getMessage().toString());
					ex.printStackTrace();
				}
			}
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH);
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			
			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}
		
		public void onDateSet(DatePicker view, int year, int month, int day) {
			Calendar calendar = new GregorianCalendar();
		// Do something with the date chosen by the user
			calendar.set(year, month, day);
			
			mDateButton.setText(DateTimeParser.getDateString(DATE_FORMAT, month, day, year));
		}
	}
	
	/*****************************
	 * member class below is used to allow displaying of TimePicker Dialog window
	 * @author Tony
	 *
	 */
	class TimePickerFragments extends DialogFragment
	implements	TimePickerDialog.OnTimeSetListener	{

		public static final String TIME_FORMAT = "hh:mm a";

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default date in the picker
			Calendar calendar = new GregorianCalendar();
			if(!isAdd)
			{//if We're editing, parse the date and set the calendar according to that
				String time = getIntent().getExtras().getString(ToDoListDatabase.COL_TIME);
				try {
					calendar = DateTimeParser.parse(TIME_FORMAT, time);
				} catch (ParseException e) {
					Log.d("parse error", "error parsing bundle's date string.  Continuing with 'current' calendar.");
					e.printStackTrace();
				}
				catch (Exception ex) {
					Log.d("error in ToDoItemEdit.onCreateDialog()", ex.getMessage().toString());
					ex.printStackTrace();
				}
			}
			int hour=calendar.get(Calendar.HOUR_OF_DAY);
			int minute=calendar.get(Calendar.MINUTE);
			
			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(),this, hour, minute, false);
		}
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mTimeButton.setText(DateTimeParser.getTimeString(TIME_FORMAT, hourOfDay, minute));
		}
	}
}
